package com.guang.springbootrequestversion.config;

import com.alibaba.fastjson.support.config.FastJsonConfig;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.guang.springbootrequestversion.bean.Cat;
import com.guang.springbootrequestversion.resolver.BindHandlerMethodArgumentResolver;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.convert.converter.Converter;
import org.springframework.format.FormatterRegistry;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.util.StringUtils;
import org.springframework.web.method.support.HandlerMethodArgumentResolver;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.nio.charset.Charset;
import java.util.Date;
import java.util.List;

/**
 * @author liguang
 * @date 2022/5/12 9:48
 */
@Configuration(proxyBeanMethods = false)
public class CustomWebMvcConfigurer implements WebMvcConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(CustomWebMvcConfigurer.class);

    /**
     * 自定义参数解析器
     * @param resolvers
     */
    @Override
    public void addArgumentResolvers(List<HandlerMethodArgumentResolver> resolvers) {
        resolvers.add(0,new BindHandlerMethodArgumentResolver());
    }

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
        FastJsonConfig jsonConfig = new FastJsonConfig();
        jsonConfig.setCharset(Charset.forName("UTF-8"));
        // 字符编码转换器
        jsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
        converter.setFastJsonConfig(jsonConfig);
        converter.setDefaultCharset(Charset.forName("Utf-8"));
        converters.add(converter);
    }

    /**
     * 自定义转换器
     * @param registry
     */
    @Override
    public void addFormatters(FormatterRegistry registry) {
        registry.addConverter(new Converter<String, Cat>() {
            @Override
            public Cat convert(String source) {
                if (!StringUtils.isEmpty(source)){
                    try {
                        String[] split = source.split(",");
                        Cat cat = new Cat();
                        cat.setName(split[0]);
                        cat.setAge(Integer.parseInt(split[1]));
                        return cat;
                    }catch (Exception exception){
                        logger.error("对应的异常信息是：{},具体异常是：{}",exception.getMessage(),exception);
                    }
                }
                return null;
            }
        });
        // LocalDate与Date互转
        registry.addConverter(new Converter<String, Date>() {
            @Override
            public Date convert(String source) {
                return new Date();
            }
        });
    }
}
